<template>
  <div class="app-container">
    <div class="inputBox">
      <el-input v-model="search.title" class="input" placeholder="请输入课程标题查询" />
      <el-select v-model="search.type" placeholder="请选择课程类型">
        <el-option v-for="(item, index) in courseList" :key="index" :label="item.type == 0?'禅修':'其他'" :value="item.type" />
      </el-select>
      <el-select v-model="search.tid" placeholder="请选择讲师">
        <el-option v-for="(item, index) in teacherList" :key="index" :label="item.name" :value="item.tid" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">查询</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
      <el-button v-show="permissionShow && permissionBoolean('新增')" type="primary" @click="addCourseType">新增</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <el-table-column :show-overflow-tooltip="true" label="课程标题" width="170">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="课程类型">
        <template slot-scope="scope">
          <p v-if="scope.row.type == 0">禅修</p>
          <p v-else>其他</p>
        </template>
      </el-table-column>
      <el-table-column :formatter="(item) => formatDate('start', item)" label="开始时间" width="150"/>
      <el-table-column :formatter="(item) => formatDate('end', item)" label="结束时间" width="150" />
      <el-table-column label="讲师">
        <template slot-scope="scope">
          {{ scope.row.teacherName }}
        </template>
      </el-table-column>
      <el-table-column :formatter="(item) => formatDate('create', item)" label="发布时间" width="130" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.status | typeFilter }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="290">
        <template slot-scope="scope">
          <el-button v-show="permissionShow && permissionBoolean('查看')" size="mini" type="warning" @click="look(scope.$index)">查看</el-button>
          <el-button v-show="permissionShow && permissionBoolean('上架')" v-if="scope.row.status != 2" size="mini" type="success" @click="changeType(scope.row.cid, scope.row.status)">{{ scope.row.status == 0 ? "上架" : "下架" }}</el-button>
          <el-button v-show="permissionShow && permissionBoolean('编辑')" v-if="scope.row.status == 0" size="mini" type="primary" @click="editRow(scope.$index)">编辑</el-button>
          <!-- <el-button v-else="scope.row.status == 1" size="mini" type="info" >编辑</el-button> -->
          <!--<el-button size="mini" type="danger" @click="del(scope.row.id)">删除</el-button>-->
          <!--<el-button size="mini" type="primary" @click="enable(scope.row.id)">上架</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
  </div>
</template>

<script>
import { getCourseList, editCours, courseUpdateStatus } from '@/api/course'
import { getTeacherList } from '@/api/teacher'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import mixin from '@/mixin'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const statusMap = {
        0: '未上架',
        1: '已上架',
        2: '已结束'
      }
      return statusMap[status]
    }
  },
  mixins: [mixin],
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      search: {
        title: '',
        type: '',
        tid: ''
      },
      isShowDel: false,
      dialogFormVisible: false,
      temp: {
        status: ''
      },
      courseTypeId: null,
      course: {
        name: '',
        introduce: '',
        price: '',
        imgUrl: ''
      },
      fileList: [],
      imgSrc: '',
      actionUrl: 'https://upload-z2.qiniup.com',
      isEdit: false,
      uploadData: {
        key: '',
        token: ''
      },
      teacherList: [],
      courseList: [],
      pageQuery: { // 查询课程列表
        pageNum: 1,
        pageSize: 1000
      },
      id: '',
      uid: '',
      permissionShow: false, // 权限数据未到达之前按钮隐藏
      permissionList: [] // 权限数据列表
    }
  },
  computed: {
    permissionBoolean() {
      return function(str) {
        const arr = []
        for (let i = 0; i < this.permissionList.length; i++) {
          arr.push(this.permissionList[i].name)
        }
        const index = arr.indexOf(str)
        if (index !== -1) {
          return true
        } else {
          return false
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    // getPermission(id, params)
    this.fetchData()
    this.getTeachers()
    this.getCourses()
    this.getPermissonFn() // 接口 - 权限列表
  },
  mounted() {
    console.log('查看权限名称mounted', this.permissionList)
  },
  methods: {
    // 权限数据的获取
    getPermissonFn() {
      const id = getLocalId()
      const uid = getLocalUid()
      const data = { uid }
      getPermission(id, data).then(res => {
        console.log('权限结果', res)
        if (res.code === '200') {
          this.permissionList = res.data
          // console.log('权限名称：', this.getPermissionName(this.permissionList))
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    toReset() {
      this.search.title = ''
      this.search.type = ''
      this.search.tid = ''
    },
    // 查询
    toSearch() {
      this.listLoading = true
      console.log('toSearch', this.search)
      const newData = this.objectCon(this.listQuery, this.search)
      console.log('toSearch', newData)
      console.log(newData)
      getCourseList(newData).then(response => {
        console.log(response)
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 获取课程类型
    getCourses() {
      getCourseList(this.pageQuery).then(response => {
        console.log('课程', response)
        // this.courseList = response.data.list
        if (response.code === '200') {
          const arr = new Map();
          this.courseList = response.data.list.filter((a) => !arr.has(a.type) && arr.set(a.type, 1))
        } else {
          Message.error(response.message + '-' + response.data)
        }
      })
    },
    // 获取讲师列表
    getTeachers() {
      getTeacherList(this.pageQuery).then(res => {
        console.log(res)
        if (res.code === '200') {
          this.teacherList = res.data.list
        } else {
          // Message.error(res.message)
        }
      })
    },
    fetchData() {
      const newData = this.objectCon(this.listQuery, this.search)
      console.log('newData:', newData)
      this.listLoading = true
      getCourseList(newData).then(response => {
        console.log(response.data.list)
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    del(pid) {
      this.$confirm('确认要删除该咨询？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // delTeacherCourse(pid).then(res => {
        //   if (res.success) {
        //     this.$message({
        //       type: 'success',
        //       message: '删除成功!'
        //     })
        //     this.fetchData()
        //   }
        // })
      }).catch(() => {
      })
    },
    changeType(cid, status) {
      let newType = -1
      let str = ''
      status === 0 ? newType = 1 : newType = 0
      status === 0 ? str = '您确定上架此商品吗？' : str = '您确定下架此商品吗？'
      this.$confirm(str, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { cid, status: newType }
        courseUpdateStatus(data).then(res => {
          if (res.code === '200') {
            this.fetchData();
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          }
        })
      }).catch(() => {
      })
    },
    look(pid) {
      const that = this;
      console.log(that.$data.list[pid])
      const obj = Object.assign({ isLook: true }, that.$data.list[pid])
      this.$router.push({
        path: '/add',
        query: obj
      })
    },
    addCourse(courseTypeId) {
      this.$data.courseTypeId = courseTypeId
      this.$data.dialogFormVisible = true
    },
    getValue(value) {
      this.$data.temp.status = value
    },
    getEnable(value) {
      this.$data.course.isEnable = value
    },
    getChildren(value) {
      this.$data.course.courseList = value
    },
    addCourseType() {
      this.$router.push({
        path: '/add',
        query: {}
      })
    },
    editRow(pid) {
      const _this = this;
      const object = Object.assign({ isEdit: true }, _this.$data.list[pid])
      this.$router.push({
        path: '/add',
        query: object
      })
    }
  }
}
</script>

<style>
  .el-icon-remove {
    margin-left: 10px;
  }
  .img_url {
    width: 110px;
    height: 110px;
  }
</style>
